package uw10.app.events;

import java.util.ArrayList;

import android.content.SharedPreferences;

import uw10.app.data.Event;

public class EventManager
{
	private ArrayList<Event> events;
	private EventManager.Listener listener;
	
	public EventManager(EventManager.Listener listener)
	{
		setListener(listener);
		events = new ArrayList<Event>();
	}
	
	public void setListener(EventManager.Listener listener)
	{
		this.listener = listener;
	}
	
	public void load(SharedPreferences pref)
	{	
		events = new ArrayList<Event>();
		int i = 0;
		while (pref.contains("event_state_" + i))
		{
			Event e = new Event(
					pref.getString("event_company_" + i, "unknown"),
					pref.getInt("event_state_" + i, 0),
					pref.getInt("event_id_" + i, 0),
					pref.getInt("event_icon_" + i, 0),
					pref.getInt("event_rating_" + i, 0),
					pref.getLong("event_timestamp_" + i, 0),
					pref.getInt("event_hour_" + i, 0),
					pref.getInt("event_min_" + i, 0));
			if (e.state == Event.NEW) e.state = Event.OLD;
			events.add(e);
			i++;
		}
	}
	
	public void save(SharedPreferences pref)
	{
		SharedPreferences.Editor edit = pref.edit();
		edit.clear();
		int i = 0;
		for (Event e : events)
		{
			edit.putString("event_company_" + i, e.company);
			edit.putInt("event_state_" + i, e.state);
			edit.putInt("event_id" + i, e.id);
			edit.putInt("event_icon_" + i, e.icon);
			edit.putInt("event_rating_" + i, e.rating);
			edit.putLong("event_timestamp_" + i, e.timestamp);
			edit.putInt("event_hour_" + i, e.hours);
			edit.putInt("event_min_" + i, e.minutes);
			i++;
		}
		edit.commit();
	}
	
	public void star(Event e)
	{
		e.state = Event.STAR;
		updateListener();
	}
	
	public void unstar(Event e)
	{
		e.state = Event.OLD;
		updateListener();
	}
	
	public void delete(Event e)
	{
		events.remove(e);
		updateListener();
	}
	
	public void discard(Event e)
	{
		events.remove(e);
		updateListener();
	}
	
	public void receive(Event[] events)
	{
		for (Event e : events)
		{
			this.events.add(e);
		}
		updateListener();
	}
	
	public void trim(long expire)
	{
		ArrayList<Event> prev = events;
		events = new ArrayList<Event>();
		
		for (Event e : prev)
		{
			if (e.state == Event.STAR || e.state == Event.NEW || e.timestamp > expire)
			{
				events.add(e);
			}
		}
		updateListener();
	}
	
	public void updateListener()
	{
		if (listener != null) listener.onEventSetUpdated(events.toArray(new Event[events.size()]));
	}
	
	public static interface Listener
	{
		void onEventSetUpdated(Event[] events);
	}
}
